package com.suoluo.zenadmin.controllers;

import javax.servlet.http.HttpServletRequest;

import net.paoding.rose.web.ControllerErrorHandler;
import net.paoding.rose.web.Invocation;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.suoluo.zenadmin.common.CommonResp;
import com.suoluo.zenadmin.controllers.JSONInterceptor.JSON;
import com.suoluo.zenadmin.service.ServiceException;

public class ErrorHandler implements ControllerErrorHandler {

	private static final Log logger = LogFactory.getLog(ErrorHandler.class);
	@Override
	public Object onError(Invocation inv, Throwable e) throws Throwable {
		// inv.isAnnotationPresent(arg0)
//		MDC.put("remoteAddr", request.getRemoteAddr());
		HttpServletRequest request = inv.getRequest();
		String userAgent = request.getHeader("User-Agent");
		String ip = request.getRemoteAddr();
		String uri = inv.getRequestPath().getRosePath();
		String errorMsg = "{userAgent="+userAgent+",ip="+ip+",uri="+uri+"}";
		if (inv.isAnnotationPresent(JSON.class)) {
			if (e instanceof ServiceException) {
				ServiceException se = (ServiceException) e;
				CommonResp.encodeResp(inv, new CommonResp(se.getResultCode(),
						se.getResultMsg()));
			} else {
				CommonResp.encodeResp(inv, CommonResp.FAIL);
			}
			
			logger.error(errorMsg,e);
			return "";
		}else{
			logger.error(errorMsg,e);
			return "f:/404";
//			return "r:"+inv.getRequestPath().getCtxpath()+"/404";
		}
		
	}

//	private void encodeToJSON(Invocation invocation, Object encodeObj)
//			throws IOException {
//		HttpServletResponse response = invocation.getResponse();
//		if (response.getContentType() == null) {
//			response.setContentType("application/json;charset=UTF-8");
//		}
//		Gson gson = new Gson();
//
//		String json = gson.toJson(encodeObj);
//		response.getWriter().write(json);
//	}

}
